// useLogs.ts
import { computed, ref } from 'vue'

export interface LogEntry {
  type: 'info' | 'success' | 'warning' | 'error'
  message: string
  timestamp: number
}

export function useLogs(maxLogs = 200) {
  const logs = ref<LogEntry[]>([])
  const logsCount = ref(0)

  // 添加日志
  const addLog = (message: string, type: LogEntry['type'] = 'info') => {
    logsCount.value++
    logs.value.push({
      type,
      message,
      timestamp: Date.now()
    })

    // 限制日志数量，避免内存泄漏
    if (logs.value.length > maxLogs) {
      logs.value = logs.value.slice(0, Math.floor(maxLogs / 2))
    }
  }

  // 清空日志
  const clearLogs = () => {
    logs.value = []
    logsCount.value = 0
  }

  // 批量添加日志
  const addLogs = (newLogs: Omit<LogEntry, 'timestamp'>[]) => {
    newLogs.forEach(log => addLog(log.message, log.type))
  }

  // 获取特定类型的日志
  const getLogsByType = (type: LogEntry['type']) => {
    return logs.value.filter(log => log.type === type)
  }

  // 计算属性：各种类型日志的数量
  const logCounts = computed(() => {
    const counts = {
      info: 0,
      success: 0,
      warning: 0,
      error: 0,
      total: logs.value.length
    }

    logs.value.forEach(log => {
      counts[log.type]++
    })

    return counts
  })

  return {
    logs,
    logsCount,
    addLog,
    clearLogs,
    addLogs,
    getLogsByType,
    logCounts
  }
}